import { defineEventHandler, readBody } from 'h3'
import { getPool } from '../../util/mysql'
import { checkAdminKey } from './_utils'

export default defineEventHandler(async (event: any) => {
  const ck = await checkAdminKey(event)
  if (!ck.ok) return { status: event.node.res.statusCode || 401, message: ck.message }

  const body = await readBody(event).catch(() => ({}))
  const id = body.id ?? body.order_id ?? body.orderId
  const force = !!body.force

  if (!id) {
    event.node.res.statusCode = 400
    return { status: 400, message: 'missing order id' }
  }

  try {
    const pool = await getPool()

    // 查询订单并确认存在
    const [ordRows]: any = await pool.execute(
      `SELECT id, status, product_id FROM lin_order WHERE id = ? AND is_deleted = 0 LIMIT 1`,
      [id]
    )
    if (!Array.isArray(ordRows) || ordRows.length === 0) {
      event.node.res.statusCode = 404
      return { status: 404, message: 'order not found' }
    }

    const order = ordRows[0]

    // 简单判断是否为未支付状态。支持常见的字符串或数字标识；可用 force 强制覆盖
  const unpaidStates = new Set(['unpaid', 'pending', 'created', '0', 0, null, '', '未支付', '待支付', '未付款'])
  const statusVal = order.status === null || order.status === undefined ? '' : String(order.status).trim()
  const isUnpaid = unpaidStates.has(statusVal)
    if (!force && !isUnpaid) {
      event.node.res.statusCode = 400
      return { status: 400, message: `order status is not unpaid: ${String(order.status)}` }
    }

    // 查找对应的 product_info（如果存在 product_id）
    let productInfo: any = null
    if (order.product_id || order.product_id === 0) {
      const [pRows]: any = await pool.execute(
        `SELECT product_info FROM lin_product WHERE id = ? AND is_deleted = 0 LIMIT 1`,
        [order.product_id]
      )
      if (Array.isArray(pRows) && pRows.length > 0) productInfo = pRows[0].product_info || null
    }

    // 将订单设为已支付并更新 product_info
    const newStatus = '已支付'
    await pool.execute(`UPDATE lin_order SET status = ?, product_info = ? WHERE id = ?`, [newStatus, productInfo, id])

    // 返回更新后的订单（方便前端刷新单行）
    const [afterRows]: any = await pool.execute(`SELECT * FROM lin_order WHERE id = ? LIMIT 1`, [id])
    return { status: 200, data: (afterRows && afterRows[0]) || null }
  } catch (err: any) {
    event.node.res.statusCode = 500
    return { status: 500, message: String(err?.message || err) }
  }
})
